package com.cya.lotterysystem.controller;

import com.cya.lotterysystem.common.errcode.ControllerErrorCodeConstans;
import com.cya.lotterysystem.common.exception.ControllerException;
import com.cya.lotterysystem.common.pojo.CommonResult;
import com.cya.lotterysystem.common.utils.JacksonUtil;
import com.cya.lotterysystem.controller.param.CreateActivityParam;
import com.cya.lotterysystem.controller.param.PageParam;
import com.cya.lotterysystem.controller.reslut.CreateActivityResult;
import com.cya.lotterysystem.controller.reslut.FindActivityListResult;
import com.cya.lotterysystem.controller.reslut.FindPrizeListResult;
import com.cya.lotterysystem.controller.reslut.GetActivityDetailResult;
import com.cya.lotterysystem.service.ActivityService;
import com.cya.lotterysystem.service.PrizeService;
import com.cya.lotterysystem.service.dto.*;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.stream.Collectors;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/11/3 14:46
 * @description： 活动接口
 * @modified By：
 * @version:
 */
@Slf4j
@RestController
public class ActivityConreoller {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private PrizeService prizeService;


    /**
     * 活动创建
     * @param param
     * @return
     */
    @RequestMapping("/activity/create")
    public CommonResult<CreateActivityResult> createActivity(@Valid @RequestBody CreateActivityParam param){

        log.info("createActivity CreateActivityParam:{}", JacksonUtil.writeValueAsString(param));


           return CommonResult.success(converTOCreateActivityResult(activityService.CreateActivity(param)));




    }

    private CreateActivityResult converTOCreateActivityResult(CreateActivityDTO createActivityDTO) {

        if (createActivityDTO==null){
            throw new ControllerException(ControllerErrorCodeConstans.CREATE_ACTIVITY_ERROR);
        }

        CreateActivityResult result=new CreateActivityResult();

        result.setActivityId(createActivityDTO.getActivityId());
        return result;
    }

    @RequestMapping("/activity/find-list")
     public CommonResult<FindActivityListResult> findactivityList(PageParam param){

        log.info("findactivityList PageParam:{}",JacksonUtil.writeValueAsString(param));

        return CommonResult.success(
                converToActivityListResult(
                        activityService.findActivityList(param)));

    }

    private FindActivityListResult converToActivityListResult(PageListDTO<ActivityDTO> activityList) {

        if (activityList==null){
            throw new ControllerException(ControllerErrorCodeConstans.FIND_ACTIVITY_LIST_ERROR);
        }
        FindActivityListResult result=new FindActivityListResult();

        result.setTotal(activityList.getTotal());

        result.setRecords(
                activityList.getRecords().stream()
                        .map(activityDTO -> {
                            FindActivityListResult.ActivityInfo activityInfo=new FindActivityListResult.ActivityInfo();
                            activityInfo.setActivityId(activityDTO.getActivityId());
                            activityInfo.setActivityName(activityDTO.getActivityName());
                            activityInfo.setDescription(activityDTO.getDescription());
                            activityInfo.setValid(activityDTO.vaild());
                            return activityInfo;

                        }).collect(Collectors.toList())
        );
        return result;
    }

    @RequestMapping("/activity-detail-find")
    public CommonResult<GetActivityDetailResult> getActivityDetail(Long activityId){
        log.info("getActivityDetail activityId:{}",activityId);
        ActivityDetailDTO detailDTO = activityService.getActivityDetail(activityId);

        return CommonResult.success(converToActivityDetailResult(detailDTO));
    }

    private GetActivityDetailResult converToActivityDetailResult(ActivityDetailDTO detailDTO) {

        if (detailDTO==null){
            throw new ControllerException(ControllerErrorCodeConstans.GET_ACTIVITY_DETAIL_ERROR);
        }
            GetActivityDetailResult result=new GetActivityDetailResult();
            result.setActivityId(detailDTO.getActivityId());
            result.setActivityName(detailDTO.getActivityName());
            result.setDesc(detailDTO.getDesc());
            result.setValid(detailDTO.vaild());
            //抽奖顺序：1，2，3
            result.setPrizes(
                    detailDTO.getPrizeDTOList().stream()
                            .sorted(Comparator.comparing(prizeDTO -> prizeDTO.getTiers().getCode()))
                            .map(prizeDTO->{
                                GetActivityDetailResult.Prize prize =new GetActivityDetailResult.Prize();
                                prize.setPrizeId(prizeDTO.getPrizeId());
                                prize.setName(prizeDTO.getName());
                                prize.setDescription(prizeDTO.getDescription());
                                prize.setImageUrl(prizeDTO.getImageUrl());
                                prize.setPrice(prizeDTO.getPrice());
                                prize.setPrizeTierName(prizeDTO.getTiers().getMessage());
                                prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                                prize.setValid(prizeDTO.vaile());
                              return prize;

                            }).collect(Collectors.toList())
            );
            result.setUsers(
                    detailDTO.getUserDTOList().stream()
                            .map(userDTO -> {
                                GetActivityDetailResult.User user=new GetActivityDetailResult.User();
                                user.setUserId(userDTO.getUserId());
                                user.setUserName(userDTO.getUserName());
                                user.setStatus(userDTO.vaile());
                                return user;
                            }).collect(Collectors.toList())
            );

            return result;
    }
}